<?php

class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
    protected $_name = 'users';
    
    protected $_referenceMap = array(
    		'GeneratedUrls' => array(
    				'columns' => array('id'),
    				'refTableClass' => 'Application_Model_DbTable_Users',
    				'refColumns' => array('generated_by')
    		)
    );
    
    public function addUser($username, $password, $emailAddress, $role, $firstName, $lastName)
    {
    	$currentDate = date('Y-m-d H:i:s', time());
    	$data = array(
    			'date_created' => $currentDate,
    			'date_updated' => $currentDate,
    			'username' => $username,
    			'password' => SubfolderAccessManager_Util_Password::encryptPassword($password),
    			'email_address' => $emailAddress,
    			'role' => $role,
    			'first_name' => $firstName,
    			'last_name' => $lastName,
    	);
    	return $this->insert($data);
    }
    
    public function getUser($id)
    {
    	$id = (int) $id;
    	$row = $this->fetchRow('id = ' . $id);
    	if (!$row) {
    		throw new Exception("Could not find row $id");
    		
    	}
    	return $row->toArray();
    }
    
    public function updateUser($id, $emailAddress, $firstName, $lastName, $role)
    {
    	$currentDate = date('Y-m-d H:i:s', time());
    	$data = array(
    			'email_address' => $emailAddress,
    			'first_name' => $firstName,
    			'last_name' => $lastName,
    			'date_updated' => $currentDate,
    			'role' => $role,
    	);
    	return $this->update($data, 'id = '. (int) $id);
    }
    
    public function changeUserEmail($currentEmail, $newEmail)
    {
    	$currentDate = date('Y-m-d H:i:s', time());
    	$data = array(
    			'email_address' => $newEmail,
    			'date_updated' => $currentDate,
    	);
    	$this->update($data, 'email_address = \''. $currentEmail . '\'');
    }
    
    public function changePassword($id, $newPassword)
    {
    	$currentDate = date('Y-m-d H:i:s', time());
    	$data = array(
    			'password' => SubfolderAccessManager_Util_Password::encryptPassword($newPassword),
    			'date_updated' => $currentDate,
    	);
    	$this->update($data, 'id = '. (int) $id);
    }
    
    public function deleteUser($id)
    {
    	$this->delete('id = ' . (int) $id);
    }
}

